<?php

namespace app\model;

use think\helper\Str;
use think\Model;
use think\model\relation\HasOne;

class ProductCode extends Model
{
    public function product(): HasOne
    {
        return $this->hasOne(Product::class, "id", "pid");
    }

    public function autoCreateCode(): array
    {
        $param = request()->param();
        $data = [];
        for ($i = 0; $i < $param['number']; $i++) {
            $code = Str::random($param['lent'], 1);
            if ($param['type'] == "decama") $code = Str::random($param['lent'], 0);
            elseif ($param['type'] == "string") $code = Str::random($param['lent']);
            $data[] = [
                "code" => $code,
                "pwd" => !empty($param['setPwd']) ? Str::random() : null,
                "pid" => $param['id'],
                "state" => 1,
                "is_del" => 1
            ];
        }
        $this->saveAll($data);
        return $data;
    }

    public function codePage(): array
    {
        $param = request()->param();
        $data = $this->with(['product'])->when(!empty($param['pid']), function ($query) use ($param) {
            $query->where('pid', $param['pid']);
        })->when(!empty($param['state']), function ($query) use ($param) {
            $query->where('state', $param['state']);
        })->where(['is_del' => 1])->order(['create_time' => 'desc'])->paginate([
            'list_rows' => $param['pageSize'] ?? 100,
            'page' => $param['page'] ?? 1
        ])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }
}
